import { gql, useQuery, useMutation } from "@apollo/client"
import { message, Space, Card, Form } from "antd"
import { Link, useParams } from "react-router"
import { TextViewButton, TextDeleteButton } from "../../../../../../components/BaseRoleButtonGroups"
import DelPopover from "../../../../../../components/DelPopover"
import EditTable from "../../../../../../components/EditTable"
import FormModal from "../../../../../../components/FormModal"
import HeadBack from "../../../../../../components/HeadBack"
import useOpen from "../../../../../../hooks/useOpen"
import useRole from "../../../../../../hooks/useRole"
import { useDataSource, useColumns } from "../../../../../../hooks/useTable"
import gqlError from "../../../../../../libs/gql-error"
import { BaseFields } from "../../../../../../queries/base"
import { TestChapterFields, TestChapterEntity, TestPaperFields, TestPaperEntity } from "../../../../../../queries/test"
import { QueryTestGroupByIdResult, QueryTestGroupByIdQuery } from "../../page"
import { QueryTestByIdQuery } from "../page"

export const QueryTestChapterByIdQuery = gql`
  query QueryTestChapterById(
    $id: Int!,
    $papers: Boolean
  ){
    queryTestChapterById(
      id: $id,
      papers: $papers
    ){
      ${BaseFields}
      ${TestChapterFields}
      papers{
        ${BaseFields}
        ${TestPaperFields}
      }
    }
  }
`
export interface QueryTestChapterByIdResult {
  queryTestChapterById: TestChapterEntity
}
export const QueryTestPaperQuery = gql`
  query QueryTestPaper(
    $id: Int!
  ){
    queryTestPapers(
      id: $id
    ){
      ${BaseFields}
      ${TestPaperFields}
    }
  }
`
export interface QueryTestPaperResult {
  queryTestPapers: TestPaperEntity[]
}

const CreateTestPaperMutation = gql`
  mutation CreateTestPaper(
    $name: String!,
    $sys_test_chapterId: Int!,
    $is_free: Boolean,
    $desc: String,
    $order: Int,
    $time: Int,
  ){
    createTestPaper(
      name: $name,
      sys_test_chapterId: $sys_test_chapterId,
      is_free: $is_free,
      desc: $desc,
      order: $order,
      time: $time,
    ){
      id
    }
  }
`
const UpdateTestPaperMutation = gql`
  mutation UpdateTestPaper(
    $id: Int!,
    $name: String!,
    $is_free: Boolean,
    $desc: String,
    $order: Int,
    $status: Boolean,
    $time: Int,
  ){
    updateTestPaper(
      id: $id,
      name: $name,
      is_free: $is_free,
      desc: $desc,
      order: $order,
      status: $status,
      time: $time,
    ){
      id
    }
  }
`
const DeleteTestPaperMutation = gql`
  mutation DeleteTestPaper(
    $id: Int!
  ){
    deleteTestPaper(
      id: $id
    ){
      id
    }
  }
`

const AdminTestGroupChapterPaperPage = () => {

  const params = useParams()
  const groupId = parseInt(params.groupId || "0")
  const testId = parseInt(params.testId || "0")
  const chapterId = parseInt(params.chapterId || "0")
  const group = useQuery<QueryTestGroupByIdResult>(QueryTestGroupByIdQuery, {
    variables: {
      id: groupId
    }
  })
  const test = useQuery<QueryTestByIdQuery>(QueryTestByIdQuery, {
    variables: {
      id: testId
    }
  })
  const chapter = useQuery<QueryTestChapterByIdResult>(QueryTestChapterByIdQuery, {
    variables: {
      id: chapterId
    }
  })
  const { data, loading, refetch } = useQuery<QueryTestPaperResult>(QueryTestPaperQuery, {
    variables: {
      id: chapterId
    }
  })
  const [update, { loading: updateLoading }] = useMutation(UpdateTestPaperMutation, {
    onCompleted() {
      message.success("修改成功")
      refetch()
    },
    onError(error) {
      gqlError(error)
    },
  })
  const [del, { loading: deleteLoading }] = useMutation(DeleteTestPaperMutation, {
    onCompleted() {
      message.success(`删除成功`)
      refetch()
    },
    onError(error) {
      gqlError(error)
    },
  })
  const hasRole = useRole("/test")
  const dataSource = useDataSource([...(data?.queryTestPapers || [])]).sort((a, b) => a.order - b.order)
  const columns = useColumns([{
    title: "ID",
    dataIndex: "id"
  },
  {
    title: "名称",
    dataIndex: "name",
    type: "text"
  },
  {
    title: "状态",
    dataIndex: "status",
    type: "switch"
  },
  {
    title: "排序",
    dataIndex: "order",
    type: "number"
  },
  {
    title: "考试时长",
    dataIndex: "time",
    type: "number"
  },
  {
    title: "是否免费",
    dataIndex: "is_free",
    type: "switch"
  },
  {
    title: "描述",
    dataIndex: "desc",
    type: "text"
  },
  {
    title: "操作",
    render: (_: any, record: any) => {
      return (
        <Space>
          <Link to={`/admin/question?group=${groupId}&test=${testId}&chapter=${chapterId}&paper=${record.id}`}>
            <TextViewButton />
          </Link>
          <DelPopover
            onDelete={() => {
              del({
                variables: {
                  id: record.id
                }
              })
            }}
          >
            <TextDeleteButton />
          </DelPopover>
        </Space>
      )
    }
  }])
  const [createForm] = Form.useForm()
  const [open, onOpen, onCancel] = useOpen()
  return (
    <Card>
      <HeadBack
        href={`/admin/test/${groupId}/group/${testId}/chapter`}
      />
      <h1 className="text-2xl font-bold">
        {group.data?.queryTestGroupById.name} - {test.data?.queryTestById.name} - {chapter.data?.queryTestChapterById.name}
      </h1>
      <FormModal
        form={createForm}
        open={open}
        onCancel={onCancel}
        title="新增试卷"
        query={CreateTestPaperMutation}
        options={[{
          type: "text",
          label: "名称",
          name: "name",
          rules: [{ required: true, message: "名称不能为空" }]
        },
        {
          label: "排序",
          name: "order",
          type: "number"
        },
        {
          label: "状态",
          name: "status",
          type: "switch",
          defaultValue: true
        },
        {
          label: "是否免费",
          name: "is_free",
          type: "switch"
        },
        {
          label: "考试时长",
          name: "time",
          type: "number"
        },
        {
          label: "描述",
          name: "desc",
          type: "text"
        }
        ]}
        variables={{
          sys_test_chapterId: chapterId
        }}
        onCompleted={() => { refetch() }}
      />
      <EditTable
        dataSource={dataSource}
        loading={
          loading || updateLoading || deleteLoading
        }
        columns={columns}
        hasRole={hasRole}
        pagination={false}
        onCreate={onOpen}
        onChangeItem={(record, edit) => {
          update({
            variables: {
              ...record,
              ...edit
            }
          })
        }}
      />
    </Card>
  )
}
export default AdminTestGroupChapterPaperPage